package com.wang.data.server;

 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
 

@Component
public class WServer {
	@Autowired
	private NettyServerInitializer initizlizer;
	private static int port=9001;
	public void run() {
		EventLoopGroup bossGroup = new NioEventLoopGroup();
		EventLoopGroup workerGroup = new NioEventLoopGroup();
		try {
			ServerBootstrap serverBootstrap = new ServerBootstrap();
			serverBootstrap.group(bossGroup, workerGroup);
			serverBootstrap.channel(NioServerSocketChannel.class);
			serverBootstrap.option(ChannelOption.SO_BACKLOG, 1024);
			serverBootstrap.handler(new LoggingHandler(LogLevel.INFO));
			serverBootstrap.childOption(ChannelOption.TCP_NODELAY, true);
			serverBootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);
			serverBootstrap.childHandler(initizlizer);
			// 绑定端口,开始接收进来的连接
			ChannelFuture channelFuture = serverBootstrap.bind(port).sync();
			System.out.println("服务器启动  port=> :"+port);
			channelFuture.channel().closeFuture().sync();
		} catch (Exception e) {
			System.out.println("netty服务启动异常-" + e.getMessage());
		} finally {
			System.out.println("is closing ....");
			bossGroup.shutdownGracefully();
			workerGroup.shutdownGracefully();
		}
	}

}
